package cn.ratel.route;

import cn.ratel.ioc.IocKit;
import com.google.common.base.Preconditions;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class Controller {
	private Map<String, Action> actionMap = new HashMap<>();
	private Object controllerInstance;
	private String name;

	public Controller(String controllerName, Class controllerClass) {
		this.name = controllerName;
		this.controllerInstance = IocKit.getBean(controllerClass);
		for (Method method : controllerClass.getDeclaredMethods()) {
			if (Modifier.isPublic(method.getModifiers()) && method.getReturnType() != void.class) {
				String actionPath = method.getName();
				Preconditions.checkArgument(actionMap.get(actionPath) == null, "action path is already exist :" + actionPath);
				actionMap.put(actionPath, new Action(name, method));
			}
		}
	}

	public Action getAction(String actionName) {
		return actionMap.get(actionName);
	}

	public Object getControllerInstance() {
		return controllerInstance;
	}

	public String getName() {
		return name;
	}
}
